<template>
  <div class="AddGoods">
    <el-alert title="添加商品信息" type="info" show-icon :closable="false" center>
    </el-alert>
    <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <el-form ref="form" :model="queryInfo" label-width="100px" label-position="top">
      <el-tabs v-model="activeIndex" tab-position="left" :before-leave="Tabbefor" @tab-click="tabClicked">
        <!-- 导航栏 -->
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name" :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
            <el-input v-model="queryInfo.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price" :rules="[{ required: true, message: '请输入商品价格', trigger: 'blur' }]">
            <el-input type="Number" v-model="queryInfo.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight" :rules="[{ required: true, message: '请输入商品重量', trigger: 'blur' }]">
            <el-input type="Number" v-model="queryInfo.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number" :rules="[{ required: true, message: '请输入商品数量', trigger: 'blur' }]">
            <el-input type="Number" v-model="queryInfo.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" required>
            <el-cascader expand-trigger="hover" clearable :options="CategoriesList" :props="cascaderProps" v-model="queryInfo.goods_cat" @change="handleTabClick"></el-cascader>
          </el-form-item>
        </el-tab-pane>

        <!-- 商品参数 -->
        <el-tab-pane label="商品参数" name="1" class="Canshu">
          <el-form-item :label="item.attr_name" v-for="item in ParamsManyList" :key="item.attr_id" v-show="item.attr_vals.length!==0">
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox size="small " :label="item1" border v-for="(item1,index1) in item.attr_vals" :key=index1></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 商品属性 -->
        <el-tab-pane label="商品属性" name="2">
          <el-form-item :label="item.attr_name" v-for="item in ParamsOnlyList" :key="item.attr_id">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>

        <!-- 商品图片 -->
        <el-tab-pane label="商品图片" name="3">
          <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" :on-success="handleSuccess" :on-preview="handlePreview" :headers="headersObj" :on-remove="handleRemove" list-type="picture">

            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-tab-pane>
        <!-- 商品内容 -->
        <el-tab-pane label="商品内容" name="4">
          <!-- 富文本编辑器 -->
          <quill-editor v-model="queryInfo.goods_introduce"></quill-editor>
          <el-button type="primary" style="marginTop:15px" @click="add">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <!-- 图片 -->
      <img :src="previewPath" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'AddGoods',
  data() {
    return {
      activeIndex: '0',
      CategoriesList: null,
      ParamsManyList: null,
      ParamsOnlyList: null,
      previewPath: '',
      previewVisible: false,
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      queryInfo: {
        goods_name: '',
        goods_price: null,
        goods_weight: null,
        goods_number: null,
        goods_cat: [],  // 商品所属的分类数组
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      }
    }
  },
  created() {
    this.getCategories()
  },
  methods: {
    getCategories() {  //获取分类列表
      this.$http.get('categories').then(res => {
        if (res.data.meta.status !== 200) return
        this.CategoriesList = res.data.data
      })
    },
    handleTabClick() {  //级联选择器
      if (this.queryInfo.goods_cat.length == 3) {
      } else {
        this.queryInfo.goods_cat = []
        this.$mess('请选择三级分类', 'error')
      }
    },
    Tabbefor() {
      // if (this.activeIndex == '0') {
      //   let TabStatus = false
      //   this.$refs.form.validate((res) => {
      //     if (res) {
      //       if (this.queryInfo.goods_cat.length == 3) {
      //         TabStatus = res
      //       } else {
      //         this.$mess('请选择商品分类', 'error')
      //       }

      //     }

      //   })
      //   return TabStatus
      // }
    },
    handlePreview(file) {  //图片预览
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    handleRemove(file) {  //去除图片
      const filePath = file.response.data.tmp_path
      const i = this.queryInfo.pics.findIndex(x => {
        x.pic === filePath
      })
      this.queryInfo.pics.splice(i, 1)

    },
    handleSuccess(res) {
      const picInfo = { pic: res.data.tmp_path }
      this.queryInfo.pics.push(picInfo)
      console.log(this.queryInfo.pics)
    },
    tabClicked() {
      if (this.activeIndex == '1') {
        this.$http.get(`categories/${this.queryInfo.goods_cat[2]}/attributes`, { params: { sel: 'many' } }).then(res => {
          if (res.data.meta.status !== 200) {
            this.$mess(res.data.meta.msg, 'error')
            return
          }
          res.data.data.forEach(item => {
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          });
          this.ParamsManyList = res.data.data
          console.log(this.ParamsManyList)
        })
      } else if (this.activeIndex == '2') {
        this.$http.get(`categories/${this.queryInfo.goods_cat[2]}/attributes`, { params: { sel: 'only' } }).then(res => {
          if (res.data.meta.status !== 200) {
            this.$mess(res.data.meta.msg, 'error')
            return
          }
          this.ParamsOnlyList = res.data.data
          console.log(this.ParamsOnlyList)
        })
      } else if (this.activeIndex == '3') {
        console.log('上传图片')
      } else if (this.activeIndex == '4') {
        console.log('填写内容')
      }
    },
    add() {
      this.$refs.form.validate(valid => {
        if (!valid) return this.$mess('请填写相关信息', 'error')
        const form = _.cloneDeep(this.queryInfo)  // 深拷贝
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.ParamsManyList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.queryInfo.attrs.push(newInfo)
        })
        // 处理静态属性
        this.ParamsOnlyList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.queryInfo.attrs.push(newInfo)
        })
        form.attrs = this.queryInfo.attrs
        this.$http.post('goods', form).then(res => {
          console.log(res)
          if (res.data.meta.status !== 201) return this.$mess(res.data.meta.msg, 'error')
          this.$mess('添加商品成功', 'success')
          this.$router.push('/home/goods')
        })
        console.log(form)
      })
    }

  }
}
</script>

<style lang="less" >
.AddGoods {
  .el-steps {
    margin: 30px 0 20px 0;
  }
  .el-step__title {
    font-size: 14px;
  }
  .Canshu {
    .el-form-item {
      margin: 0 !important;
    }
  }

  .el-checkbox {
    margin: 0 !important;
    margin-right: 10px !important;
  }
  .ql-editor {
    min-height: 300px;
  }
}
</style>